<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <el-row>
        <el-col :span="12">
          <el-form-item :label="$t('申请标题')" prop="actTitle">
            <el-input v-model="form.actTitle" :placeholder="$t('申请标题')" show-word-limit maxlength="50" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('申请人')" prop="userId">
            <UserSelect v-model="form.userId" :placeholder="$t('申请人')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('所属公司')" prop="company">
            <tree-select
              v-model="form.company"
              :default-expand-all="true"
              node-key="id"
              :data="companyOptions"
              :placeholder="$t('请选择')"
            >
              <label
                slot="option-label"
                slot-scope="{ node, shouldShowCount, count, labelClassName, countClassName }"
                :class="labelClassName"
              >
                {{ $t(node.label) }}
                <span v-if="shouldShowCount" :class="countClassName">({{ count }})</span>
              </label>
            </tree-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('所属部门')" prop="department">
            <dept-select
              v-model="form.department"
              :default-expand-all="true"
              :data="deptOptions"
              :placeholder="$t('请选择')"
            >
              <label
                slot="option-label"
                slot-scope="{ node, shouldShowCount, count, labelClassName, countClassName }"
                :class="labelClassName"
              >
                {{ $t(node.label) }}
                <span v-if="shouldShowCount" :class="countClassName">({{ count }})</span>
              </label>
            </dept-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('合同名称')" prop="contractId">
            <el-select v-model="form.contractId" :placeholder="$t('合同名称')" filterable clearable @change="contractChange">
              <el-option
                v-for="item in dealFixedAssetsContractList"
                :key="item.id"
                :label="$t(item.contractName)"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('支付主体')" prop="investMain">
            <MainBodySelect
              v-model="form.investMain"
              :parameters="form.investMainType"
              disabled
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('申请支付金额') + $t('金额单位')" prop="requestPaymentAmount">
            <Money v-model="form.requestPaymentAmount" unit="w" :placeholder="$t('申请支付金额')" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('支付条件满足情况')" prop="meetPaymentTerms">
            <el-input v-model="form.meetPaymentTerms" type="textarea" :placeholder="$t('支付条件满足情况')" show-word-limit maxlength="1000" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('支付摘要')" prop="abstracts">
            <el-input v-model="form.abstracts" type="textarea" :placeholder="$t('支付摘要')" show-word-limit maxlength="1000" />
          </el-form-item>
        </el-col>
      </el-row>

      <!--支付明细-->
      <div class="area-header">
        <span class="area-header-title">{{ $t('支付明细') }}</span>
      </div>
      <el-table
        :data="form.dealFixedAssetsPaymentDetails"
        border
        class="nowrapTable formTable "
        style="overflow: auto;"
        :summary-method="summaryMethod"
        show-summary
      >
        <el-table-column :label="$t('序号')" align="center" width="50">
          <template slot="header" slot-scope="{}">
            <span>{{ $t('序号') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item
              type="index"
              v-html="scope.$index + 1"
            />
          </template>
        </el-table-column>
        <el-table-column align="center" min-width="150px">
          <template slot="header" slot-scope="{}">
            <span>{{ $t('科目代码') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'dealFixedAssetsPaymentDetails.' + scope.$index + '.subjectCode'" :rules="dealFixedAssetsPaymentDetailsRules.subjectCode">
              <el-input v-model="scope.row.subjectCode" :placeholder="$t('科目代码')" disabled />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('科目名称')" align="center" min-width="180px">
          <template slot="header" slot-scope="{}">
            <i style="color: #ff4949;margin-right: 4px;">*</i>
            <span>{{ $t('科目名称') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'dealFixedAssetsPaymentDetails.' + scope.$index + '.costBudgetArray'" :rules="dealFixedAssetsPaymentDetailsRules.costBudgetArray">
              <el-cascader
                v-model="scope.row.costBudgetArray"
                :options="dealCostBudgetList"
                clearable
                @change="payTypeChange(scope.$index)"
              >
                <template slot-scope="{ node, data }">
                  <span>{{ $t(data.subjectName) }}</span>
                  <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
                </template>
              </el-cascader>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('申请支付金额') + $t('金额单位')" align="center" min-width="140">
          <template slot="header" slot-scope="{}">
            <i style="color: #ff4949;margin-right: 4px;">*</i>
            <span>{{ $t('申请支付金额') }}{{ $t('金额单位') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'dealFixedAssetsPaymentDetails.' + scope.$index + '.requestPaymentAmount'" :rules="dealFixedAssetsPaymentDetailsRules.requestPaymentAmount">
              <Money v-model="scope.row.requestPaymentAmount" unit="w" @change="percentageCalculation" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column v-if="!otherBtnHide" fixed="right" :label="$t('操作')" align="center">
          <template slot-scope="scope">
            <el-button v-hasPermi="['fixedAssets:payment:remove']" size="small" type="text" icon="el-icon-delete" @click="delHandle(scope.$index, scope.row)" />
          </template>
        </el-table-column>
      </el-table>
      <div v-if="!otherBtnHide" class="tol">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="addDetails">{{ $t("添加明细") }}</el-button>
      </div>

      <!-- 附件列表 -->
      <FileTable :list.sync="form.fileList" data-type="deal_fixed_assets_payment" :business-id="form.dealId" :btn-show="!otherBtnHide" />
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: right;">
      <!--保存，保存并启动流程，取消 三个按钮-->
      <FormBtn ref="formBtn" :bus-data="form" has-permi="fixedAssets:payment" />
    </div>
  </div>
</template>

<script>
import {
  saveDealFixedAssetsPayment,
  getDealFixedAssetsPayment,
  delDealFixedAssetsPaymentDetails
} from '@/api/deal/fixedAssets/dealFixedAssetsPayment'
    import { treeselect } from '@/api/system/dept'
    import { listTreeInDealCostBudget } from '@/api/deal/fixedAssets/dealCostBudget'
    import { listDealFixedAssetsContract } from '@/api/deal/fixedAssets/dealFixedAssetsContract'
    import TreeSelect from '@/components/TreeSelect'
    import MainBodySelect from '@/components/MainBodySelect'
    export default {
      components: {
        TreeSelect,
        MainBodySelect
      },
        data() {
            return {
                // 表单参数
                form: {
                  dealFixedAssetsPaymentDetails: []
                },
                // 表单校验
                rules: {
                  actTitle: [{ required: true, message: this.$t('必填信息'), 	trigger: 'blur' }],
                  userName: [{ required: true, message: this.$t('必填信息'), 	trigger: 'blur' }],
                  company: [{ required: true, message: this.$t('必填信息'), 	trigger: 'blur' }],
                  department: [{ required: true, message: this.$t('必填信息'), 	trigger: 'blur' }],
                  contractId: [{ required: true, message: this.$t('必填信息'), 	trigger: 'blur' }],
                  investMain: [{ required: true, message: this.$t('必填信息'), 	trigger: 'blur' }],
                  requestPaymentAmount: [{ required: true, message: this.$t('必填信息'), 	trigger: 'blur' }]

                },
                dealFixedAssetsPaymentDetailsRules: {
                  costBudgetArray: [{ required: true, message: this.$t('必填信息'), 	trigger: 'blur' }],
                  requestPaymentAmount: [{ required: true, message: this.$t('必填信息'), 	trigger: 'blur' }]
                },
                // 公司树
                companyOptions: [],
                // 部门树
                deptOptions: [],
                dealCostBudgetList: [],
                // 关联合同下拉
                dealFixedAssetsContractList: [],
                // 遮罩层
                loading: false,
                // 操作按钮默认不展示
                buttonShow: true,
                // 是否隐藏其它按钮
                otherBtnHide: false
            }
        },
        created() {
            this.$bus.$emit('async_done')
            treeselect({ 'deptType': 'GS' }).then(response => {
              this.companyOptions = response.data
            })
            listDealFixedAssetsContract({ dealId: this.form.dealId, actStatus: 'W' }).then(response => {
              this.dealFixedAssetsContractList = response.rows
              this.total = response.total
            })
            listTreeInDealCostBudget({ dealId: this.$route.query.id }).then(response => {
              var data = response.rows
              // 国际化
              data.forEach(item => {
                item.label = this.$t(item.label)
                item.children.forEach(item2 => {
                  item2.label = this.$t(item2.label)
                })
              })
              this.dealCostBudgetList = data
            })
        },
        methods: {
            // 初始化数据
            init(data) {
                this.loading = true
                if (data != null && data.id !== undefined) {
                    getDealFixedAssetsPayment(data.id).then(response => {
                        this.form = response.data
                        for (let i = 0; i < this.form.dealFixedAssetsPaymentDetails.length; i++) {
                          const type = this.form.dealFixedAssetsPaymentDetails[i]
                          this.$set(this.form.dealFixedAssetsPaymentDetails[i], 'costBudgetArray', [])
                          this.form.dealFixedAssetsPaymentDetails[i].costBudgetArray.push(type.costBudgetOne)
                          this.form.dealFixedAssetsPaymentDetails[i].costBudgetArray.push(type.costBudgetTwo)
                          this.payTypeChange(i)
                        }
                        this.loading = false
                    }).catch(() => {
                        this.loading = false
                    })
                } else {
                    this.reset()
                    this.loading = false
                }
            },
            // 表单重置
            reset() {
                this.form = {
                    id: undefined,
                    dealId: this.$route.query.id,
                    actTitle: undefined,
                    userId: undefined,
                    company: undefined,
                    department: undefined,
                    contractId: undefined,
                    investMainType: undefined,
                    investMain: undefined,
                    requestPaymentAmount: undefined,
                    meetPaymentTerms: undefined,
                    abstracts: undefined,
                    actId: undefined,
                    actStatus: undefined,
                    createBy: undefined,
                    createTime: undefined,
                    updateBy: undefined,
                    updateTime: undefined,
                    delFlag: undefined
                }
                this.resetForm('form')
            },
            // 取消按钮
            cancel() {
                this.$parent.$parent.formOpen = false
                this.$parent.$parent.reset()
            },
            // 关闭form页面
            closeForm() {
                // 关闭form页面遮罩层
                this.loading = false
                // 关闭form页面
                if (this.$parent.$parent.formOpen !== undefined) {
                    this.$parent.$parent.formOpen = false
                }
                // 刷新list页面
                if (this.$parent.$parent.getList !== undefined) {
                  this.$parent.$parent.getList()
                }
            },
            /** 提交按钮 */
            submitForm(type) {
                return new Promise((resolve, reject) => {
                  this.$refs['form'].validate(valid => {
                    // 验证数据
                    if (valid) {
                      // 弹出遮罩层
                      this.loading = true
                      // 保存数据
                      saveDealFixedAssetsPayment(this.form).then(response => {
                        if (response.code === 200) {
                          // 点击的按钮是保存并启动流程
                          if (type === 'process') {
                            // 启动流程
                            this.startProcess(response.data.id)
                            // 点击的仅保存
                          } else {
                            this.msgSuccess(this.$t('保存成功'))
                            // 关闭form页面
                            this.closeForm()
                          }
                          resolve()
                        } else {
                          this.msgError(response.msg)
                          this.loading = false
                          reject()
                        }
                      })
                    } else {
                      reject()
                      this.locationError(document)
                    }
                  })
                }).catch(() => {
                    this.loading = false
                })
           },
            // 启动流程
           startProcess(dataId) {
               this.loading = false
               // 启动流程时候传入的参数
               const processData = {}
               // 待办标题
               processData.title = this.form.actTitle
               // 业务表名
               processData.dataTable = 'deal_fixed_assets_payment'
               // 业务ID
               processData.dataId = dataId
               // 业务表单地址(待办页面需要打开的页面)
               processData.formPath = '@/views/deal/fixedAssets/payment/dealFixedAssetsPaymentForm'
               // 菜单标识(根据菜单标识判断的走哪个流程)
               processData.menuKey = 'deal_fixed_assets_payment'
               this.startProcessByMenu(processData, () => {
                   this.form.actStatus = 'D'
                   this.msgSuccess(this.$t('数据保存成功,流程启动成功'))
                   this.closeForm()
               })
           },
            // 添加预算明细
            addDetails() {
              const row = {
                id: undefined,
                costBudgetArray: [],
                subjectCode: '',
                subjectName: '',
                requestPaymentAmount: 0,
                actualPaymentAmount: 0,
                actualPaymentTime: undefined
              }
              if (!(this.form.dealFixedAssetsPaymentDetails instanceof Array)) {
                this.$set(this.form, 'dealFixedAssetsPaymentDetails', [])
              }
              this.$nextTick(() => {
                this.form.dealFixedAssetsPaymentDetails.push(row)
              })
            },
            // 删除预算明细
            delHandle(index, row) {
              const that = this
              const id = row.id
              if (id !== undefined && id !== '' && id != null) {
                this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
                  confirmButtonText: this.$t('确定'),
                  cancelButtonText: this.$t('取消'),
                  type: 'warning'
                }).then(function() {
                  return delDealFixedAssetsPaymentDetails(id).then(response => {
                    if (response.code === 200) {
                      that.form.dealFixedAssetsPaymentDetails.splice(index, 1)
                      that.percentageCalculation()
                      return that.msgSuccess(that.$t('删除成功'))
                    }
                  })
                })
              } else {
                that.form.dealFixedAssetsPaymentDetails.splice(index, 1)
                that.percentageCalculation()
              }
            },
            // 获取明细合计
            summaryMethod() {
              let sum = 0
              this.form.dealFixedAssetsPaymentDetails.forEach(item => {
                sum += item.requestPaymentAmount
              })
              return sum
            },
            // 计算合计是总额
            getSummaries() {
              let sum = 0
              this.form.dealFixedAssetsPaymentDetails.forEach(item => {
                sum += +item.requestPaymentAmount
              })
              this.$set(this.form, 'requestPaymentAmount', sum)
              return sum
            },
            // 计算付款主体的百分比
            percentageCalculation() {
              var temp = 0
              this.form.dealFixedAssetsPaymentDetails.forEach(item => {
                temp += item.requestPaymentAmount
              })
              var noLastRatio = 0.0
              this.form.dealFixedAssetsPaymentDetails.forEach((item, index) => {
                var ratioTemp = (item.requestPaymentAmount / temp) * 100
                if (isNaN(ratioTemp)) {
                  ratioTemp = 0
                }
                item.ratio = ratioTemp.toFixed(4)
                if (this.form.dealFixedAssetsPaymentDetails === null) {
                  this.form.dealFixedAssetsPaymentDetails = ''
                }
                if (index === this.form.dealFixedAssetsPaymentDetails.length - 1 && !isNaN(noLastRatio)) {
                  if (parseFloat(item.ratio) <= 0) {
                    item.ratio = 0
                  } else {
                    item.ratio = (100.0000 - noLastRatio).toFixed(4)
                  }
                } else {
                  noLastRatio += parseFloat(item.ratio)
                }
              })
              this.getSummaries()
            },
            // 付款类型的onchang时间
            payTypeChange(value) {
              let vals = this.form.dealFixedAssetsPaymentDetails[value].costBudgetArray
              this.form.dealFixedAssetsPaymentDetails[value].subjectCode = ''
              this.dealCostBudgetList.forEach(item => {
                if (vals === undefined) {
                  var temp = []
                  temp.push('-1')
                  vals = temp
                }
                item.children.forEach(itemTwo => {
                  if (itemTwo.id === vals[1]) {
                    this.form.dealFixedAssetsPaymentDetails[value].subjectCode = itemTwo.subjectCode
                  }
                })
              })
            },
            contractChange(value) {
              const contractNum = this.dealFixedAssetsContractList.findIndex((item) => {
                return item.id === value
              })
              this.form.investMainType = this.dealFixedAssetsContractList[contractNum].contractMainType
              this.form.investMain = this.dealFixedAssetsContractList[contractNum].contractMain
            }

        }

    }
</script>
